<template>
  <!-- 提现管理 -->
  <div class="home-page-container">
    <!-- notice 公告-->
    <el-card shadow="never">
      <div class="notice-wrapper">
        <i class="el-icon-message-solid"></i>
        <div class="info">
          <el-carousel height="112px" direction="vertical" :autoplay="true" :interval="6000" indicator-position="none" arrow="never">
            <el-carousel-item v-for="(item,index) in notice" :key="index" class="info-item">
              <!-- 兼容宙斯html标签的返回 -->
              <p v-html="item"></p>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-card>
    <!-- 禁止提现提示 -->
    <div class="no-withdraw g-flex-c" v-if="noWithdrawStr">
      <i class="el-icon-warning"></i>
      <p class="content">{{noWithdrawStr}}</p>
    </div>
    <!-- <el-card shadow="hover" class="account-card"> -->
      <div class="account-wrapper">
        <!-- account money 账户资金 -->
        <div class="g-flex-column-c money">
          <div v-if="allAccounts.length > 1" class="account">
            <el-select v-model="validAccount" @change="changeAccount">
              <el-option v-for="(item,index) in allAccounts" :key="index" :label="item.accountName" :value="item.accountCode"></el-option>
            </el-select>
          </div>
          <div v-else class="account">当前账户余额</div>
          <div class="number">¥ {{accountInfo.balance}}</div>
          <!-- <div class="detail" @click="gotoDetail">资金明细 > </div> -->
        </div>
        <!-- withdraw 提现 -->
        <div class="withdraw">
          <el-form ref="withdrawForm" :model="withdrawForm" :rules="formRules" size="mini">
            <el-row>
              <el-col :span="10">
                <el-form-item label="" prop="">
                  <el-radio-group v-model="autoWithdraw.flag">
                    <el-radio :label="1">自动提现</el-radio>
                    <el-radio :label="0">手动提现</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-show="autoWithdraw.flag === 1">
                  <!-- 若需显示具体时间，下述可改 -->
                  <el-link icon="el-icon-edit" @click="autoConfig" class="auto-edit" :disabled="!!noWithdrawStr || !isAccountValid">{{autoTimeInfo}}</el-link>
                </el-form-item>
              </el-col>
              <el-col :span="14" v-if="autoWithdraw.flag === 0">
                <el-form-item label="金额" label-width="65px" prop="amount">
                 <el-input placeholder="请输入金额,保留两位小数" v-model="withdrawForm.amount" maxlength="15" clearable @blur="getServiceFee"></el-input>
                 <div class="service-fee">手续费：{{serviceFee || '0.00'}} 元</div>
                </el-form-item>
                <el-form-item label="附言" label-width="65px">
                 <el-input type="textarea" placeholder="请输入15字以内附言" v-model="withdrawForm.remark" maxlength="15" show-word-limit clearable></el-input>
                </el-form-item>  
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- account info 账户信息 -->
        <div class="info">
          <el-form label-width="100px">
            <el-form-item label="账户名称：">
              <span>{{accountInfo.bankCardInfo.companyName || ''}}</span>
            </el-form-item> 
            <el-form-item label="提现账户：">
              <span>{{accountInfo.bankCardInfo.accountName || ''}}</span>
            </el-form-item> 
            <el-form-item label="提现账号：">
              <span style="margin-right:5px">{{accountInfo.bankCardInfo.accountNo || ''}}</span>
              <el-tooltip class="item" effect="dark" content="如需更改银行卡号、账户信息，请联系相关业务人员协助您操作。" placement="top-end">
                <i class="el-icon-info"></i>
              </el-tooltip>
            </el-form-item> 
          </el-form>
        </div>
      </div>
    <!-- </el-card> -->
    <!-- 提交按钮 -->
    <div class="submit-wrapper" v-show="autoWithdraw.flag === 0">
      <el-button type="primary" class="submit-btn" :loading="submitLoading" @click="checkSubmit" :disabled="!!noWithdrawStr">点击提现</el-button>
    </div>
    <!-- 自动提现配置 -->
    <withdraw-config v-if="dialogFlag==='config'" :info="withdrawInfo" @close="dialogFlag='';getCurrentAccountInfo()"></withdraw-config>
    <!-- 中顺易统一协议 -->
    <withdraw-agreement v-if="dialogFlag==='zsy'" @close="dialogFlag='';getCurrentAccountInfo()" @exit="gotoHome()"></withdraw-agreement>
    <!-- 平安鉴权 -->
    <withdraw-auth v-if="dialogFlag==='auth'" :bankForm="authInfo" @close="dialogFlag='';getCurrentAccountInfo()" @exit="gotoHome()"></withdraw-auth>
  </div>
</template>
<script>
import { getAllD0AccountApi, getAccountInfoApi, withdrawSubmitApi, getServiceFeeApi, isAllowWithdrawApi } from '@/api/finance'
import WithdrawAgreement from './components/withdraw/agreement'
import WithdrawConfig from './components/withdraw/config'
import WithdrawAuth from './components/withdraw/authentication'
import accountMix from '@/views/finance/mixins/account'

export default {
  // name: 'finance_withdraw',
  mixins:[ accountMix ],
  components:{
    WithdrawAgreement,
    WithdrawConfig,
    WithdrawAuth
  },
  data(){
    var validateMoney = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入提现金额'));
      } else if( Number(value) > this.accountInfo.balance){
        callback(new Error('提现金额不可大于账户余额'))
      }else{
        callback()
      }
    }
    return {
      noWithdrawStr: '',     //不能提现原因
      notice: [],
      allAccounts: [],
      validAccount:'',
      currentAccount: {},
      autoWithdraw: {      
        flag: 0,
        time: '',
      },
      withdrawInfo: {},
      withdrawForm:{
        amount:'',
        remark:''
      },
      serviceFee: '0.00',
      formRules:{
        amount:[
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { pattern: /^\d+(\.\d{0,2})?$/, message: '请输入正确金额,且最多保留两位小数', trigger: 'blur' },
          { validator: validateMoney, trigger: 'blur' }
        ]
      },
      accountInfo:{
        balance: 0,
        autoWithdraw: false, //是否自动提现
        autoWithdrawInfo:'', //自动提现信息
        bankCardInfo:{},  //银行卡信息
        announcement:''  //公告信息
      },
      // zsy (中顺易) ｜ config （自动提现配置） ｜ auth (平安鉴权)
      dialogFlag:'',
      authInfo:'',   //平安鉴权
      submitLoading: false,
      isAccountValid: true
    }
  },
  computed: {
    autoTimeInfo (){
      return this.autoWithdraw.time ?  `每天 ${this.autoWithdraw.time} 自动提现` : '自动提现配置'
    }
  },
  created(){
    this.isAllowWithdraw()
    this.getAllAccount()
  },  
  methods:{
    // 判断当前账户是否可提现
    async isAllowWithdraw () {
      try {
        const { code, result } = await isAllowWithdrawApi()
        if (code !== 200) return
        this.noWithdrawStr = result
      } catch (error) {
        console.log(error.message)
      }
    },
    // 获取当前商户D0账户 companyId（商户ID） ｜ gasId（油站ID）
    async getAllAccount(){
      try{
        // 返回 account(账户类型) valid（是否当前生效的账户,生效账户只有一个） true生效中
        const { code, result = [] } = await getAllD0AccountApi()
        if(code !== 200) return
        this.allAccounts = result
        let tempAccount = this.allAccounts.filter(item => item.valid === true)
        if(tempAccount.length){
          // 筛选出生效账户
          this.currentAccount = tempAccount[0]
          const {accountCode,accountName} = this.currentAccount
          this.validAccount = accountCode
          //无生效账户，不获取账户信息
          if( !accountName ){
            this.$message.warning('无生效账户')
            return
          }
          // 存放到vuex
          this.dispatchAccountCode(this.currentAccount.accountCode)
          this.getCurrentAccountInfo(this.currentAccount.accountCode)
        }
        
      }catch(err){
        console.log(err)
      }
    },
    //获取当前账户信息
    /**
     * @params {boolean} isAuth 是否鉴权
     * 切换当前不生效的账户不需要鉴权
     */
    async getCurrentAccountInfo(isAuth = true){
      let data = {}
      data.accountCode = this.currentAccount.accountCode ? this.currentAccount.accountCode : this.account_code
      try{
        const { code,result = {} } = await getAccountInfoApi(data)
        if(code !== 200) return
        this.accountInfo = result
        this.initWithdraw(result)
        // 是否为冻结账户，冻结账户执行冻结操作
        // 是否启用（中顺易需要同意开户协议，平安需要鉴权） enable true已启用 false需开通或鉴权  华夏自动绑定
        if(!result.enable && isAuth){
          this.trafficPage(this.currentAccount.accountCode)
        }
      }catch(err){
        console.log(err)
      }
    },
    //判断当前商户或油站该如何显示 开通协议，未开通协议
    // 2 中顺易 ｜ 1 平安 ｜ 0 华夏(会后端报错处理，没有账户信息)
    trafficPage(accountCode){
      let authInfnData = {}
      switch(accountCode){
        case 2: this.dialogFlag = 'zsy'; break
        case 1: 
          authInfnData = {
            ...this.accountInfo.bankCardInfo,
            peaceAuthPage: this.accountInfo.peaceAuthPage,  //需要显示对状态
            verifyNum: this.accountInfo.verifyNum,      //剩余鉴权次数
            waitSeconds: this.accountInfo.waitSeconds    //需要等待的秒数
          }
          this.dialogFlag = 'auth'
          this.authInfo = authInfnData
          break
        default: 
          this.dialogFlag = ''
      }  
    },
    //初始化提现方式
    initWithdraw(accountInfo){
      // 获取公告 ['公告中']
      this.notice = (accountInfo.announcement && accountInfo.announcement.length) ? accountInfo.announcement : []
      this.autoWithdraw.flag = accountInfo.autoWithdraw ? 1 : 0 
      this.autoWithdraw.time = accountInfo.withdrawTime
      // 是否冻结
      this.freezeAccount(this.currentAccount)
    },
    //切换商户结算方式
    changeAccount(accountCode){
      let tempAccount = this.allAccounts.filter(item => item.accountCode === accountCode )
      if(tempAccount.length){
        // 不生效账户，禁止设置自动提现配置
        // this.isAccountValid = tempAccount[0].valid
        this.currentAccount = tempAccount[0]
        // 存放到vuex
        this.dispatchAccountCode(this.currentAccount.accountCode)
        this.getCurrentAccountInfo(false)
      }
    },
    // 获取手续费
    // 暂时只有华夏有
    async getServiceFee(){
      if(!this.withdrawForm.amount) return
      if(!/^\d+(\.\d{0,2})?$/.test(this.withdrawForm.amount)) return
      try{
        const data = {
          account: this.currentAccount.accountCode,
          amount: Number(this.withdrawForm.amount)
        }
        const {code,result} = await getServiceFeeApi(data)
        if(code !== 200) return
        this.serviceFee = result
      }catch(e){
        console.log(e)
      }
    },
    //check 提交之前的一些校验
    checkSubmit(){
      //do something
      if(!this.currentAccount){
        return this.$message.warning('请确认当前账户是否生效')
      }
      this.$refs['withdrawForm'].validate((valid) => {
        if(valid){
          const data = { 
            ...this.withdrawForm, 
            accountCode: this.currentAccount.accountCode 
          }
          this.withdrawSubmit(data)
        }
      })
    },
    async withdrawSubmit(data){
      try{
        this.submitLoading = true
        const { code, result = {} } = await withdrawSubmitApi(data)
        console.log(result)
        if(code === 200){
          this.$message.success('提现申请成功, 100万以下一般实时到账，最晚2小时内到账，请注意查看您银行卡账户余额');
          this.getCurrentAccountInfo()   //获取账户，获取余额
        } 
      }catch(err){
        console.log(err)
      }finally{
        this.submitLoading = false
      }
    },
    gotoDetail(){
      this.$router.push({path:'/finance/withdrawDetail'})
    },
    autoConfig(){
      this.dialogFlag = 'config'
      const { autoWithdraw, withdrawTime } = this.accountInfo
      this.withdrawInfo = {
        autoWithdraw,
        withdrawTime: withdrawTime  || '00:00',
        accountCode: this.currentAccount.accountCode
      }
    },
    gotoHome(){
      // 修改,肯定有订单列表页
      this.$router.push({path:'/order/orderList'})
    },
    //处理需要冻结的账户,不允许提现，并展示错误原因
    /**
     * accountStatus:  账户状态，0 冻结，1 正常
     * clues: 冻结原因
     */
    freezeAccount({accountStatus,clues}){
      if(accountStatus === 1) return
      //展示提现原因，禁止提现，兼容无返回原因
      this.noWithdrawStr = clues || '请联系相关人员'    
    }
  }
}
</script>
<style lang="less" scoped>
.home-page-container{
  margin-top: 20px;
}
.notice-wrapper{
  display: flex;
  align-items: center;
  .info{
    margin-left: 10px;
    color: #222;
    font-size: 14px;
    line-height: 1.25;
    width: 100%;
    .info-item{
      display: flex;
      align-items: center;
      span{
        word-break: break-all;
      }
    }
  }
}
.account-card{
  margin-top: 20px;
  margin-bottom: 67px;
}
.account-wrapper{
  margin-top: 10px;
  margin-bottom: 67px;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  & > div{
    height: 160px;
    box-sizing: border-box;
    border-radius: 2px;
    background:rgba(255,255,255,1);
  }
  .money{
    width: 18%;
    flex-wrap: nowrap;
    .account{
      font-size: 20px;
      color: #222222;
      font-weight: 500;
    }
    .number{
      font-size: 22px;
      color: #222222;
      margin: 15px 0 0;
    }
    .detail{
      font-size: 14px;
      color: #A6A6A6;
      cursor: pointer;  
    }
  }
  .withdraw{
    // width: 574px;
    width: 50%;
    padding: 17px 30px;
    margin: 0 15px;
  }
  .info{
    // width: 381px;
    width: 30%;
    .el-form-item {
      margin-bottom: 12px;
    }
  }
}
.submit-wrapper{
  width: 100%;
  .submit-btn{
    display: block;
    margin: 0 auto;
    width: 184px;
    height: 40px;
  }
}
.auto-edit{
  font-size: 12px;
}
.service-fee{
  font-size: 12px;
  color: #222;
}
.no-withdraw{
  width: 100%;
  margin-top: 10px;
  padding: 5px 15px;
  background: #FFEDED;
  border-radius: 2px;
  font-size: 14px;
  color: #FF2929;
  word-break: break-all;
  .content{
    margin-left: 15px;
  }
}
</style>